using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Text;
using StructureMap;
using SubSonic;

using Impact.Infrastructure.Configuration;
using Impact.Model.Objects;
using Impact.Model.Service;

namespace Impact.Controllers
{
    /// <summary>
    /// Controller responsible for searching the site and returning the results
    /// </summary>
    public class SearchController
    {

        /// <summary>
        /// Executes a search on the site using the terms passed in
        /// </summary>
        /// <returns>a list of searchresult objects.  each searchresult contains information
        /// about data found by the search</returns>
        public static List<SearchResult> Execute( string terms )
        {
            List<SearchResult> results = new List<SearchResult>();

            // step one - go through active ImpactPages
            IPageService pageService = ObjectFactory.GetInstance<IPageService>();
            ImpactPageCollection pages = pageService.FetchByTerms( terms );

            // put them in the results list
            foreach ( ImpactPage page in pages )
            {
                DateTime? updated = page.ModifiedOn ?? page.CreatedOn;
                results.Add( new SearchResult( page.Title, page.Body, ContentPresenter.FormatUrl( page ), updated.Value ) );
            }

            // step two - go through active Articles
            IArticleService articleService = ObjectFactory.GetInstance<IArticleService>();
            ArticleCollection articles = articleService.FetchByTerms( terms );

            // put them in the results list
            foreach ( Article article in articles )
            {
                DateTime updated = article.ModifiedOn ?? article.CreatedOn;
                results.Add( new SearchResult( article.Title, article.Body, ContentPresenter.FormatUrl( article ), updated ) );
            }

            // step three - sort descending by date
            results.Sort( delegate( SearchResult a, SearchResult b )
            {
                return b.LastUpdated.CompareTo( a.LastUpdated );
            } );

            return results;
        }

        /// <summary>
        /// Retrieve the template used for displaying search results
        /// </summary>
        /// <returns></returns>
        public static ImpactPage GetSearchTemplate()
        {
            IConfigProvider config = ObjectFactory.GetInstance<IConfigProvider>();
            IPageService pageService = ObjectFactory.GetInstance<IPageService>();
            return pageService.FetchByKey( config.Settings.SearchTemplate );
        }


    }

}
